<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;
use app\service\TopviewApiService;
use app\service\OssService;

class SyncProductBackgroundTemplates extends Command
{
    protected function configure()
    {
        $this->setName('sync:product-background-templates')
            ->setDescription('每日同步 Product AnyShoot 背景模板，下载图片并上传OSS，入库供查询');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('开始同步 Product Background 模板...');
        $api = new TopviewApiService();
        $oss = new OssService();

        $pageNo = 1;
        $pageSize = 100;
        $totalSynced = 0;

        try {
            do {
                $result = $api->getProductBackgroundTemplateList([
                    'pageNo' => $pageNo,
                    'pageSize' => $pageSize,
                ]);

                $list = $result['data'] ?? ($result['list'] ?? []);
                $total = $result['total'] ?? count($list);
                if (empty($list)) {
                    break;
                }

                foreach ($list as $item) {
                    try {
                        $uniqueKey = $item['uniqueKey'] ?? md5(($item['templateId'] ?? '') . '|' . ($item['templateImageUrl'] ?? ''));
                        $templateImageUrl = $item['templateImageUrl'] ?? '';
                        $ossUrl = null;
                        if ($templateImageUrl) {
                            $content = @file_get_contents($templateImageUrl);
                            if ($content !== false) {
                                $tmp = tempnam(sys_get_temp_dir(), 'tpl_');
                                file_put_contents($tmp, $content);
                                try {
                                    $object = 'product_background/templates/' . date('Ymd') . '/' . $uniqueKey . '.jpg';
                                    $ossUrl = $oss->putObject($object, $tmp);
                                } finally {
                                    @unlink($tmp);
                                }
                            }
                        }

                        // upsert
                        $now = date('Y-m-d H:i:s');
                        $data = [
                            'unique_key' => $uniqueKey,
                            'template_id' => $item['templateId'] ?? null,
                            'category_id' => $item['categoryId'] ?? null,
                            'category_name' => $item['categoryName'] ?? null,
                            'prompt' => $item['prompt'] ?? null,
                            'original_image_url' => $templateImageUrl,
                            'image_url' => $ossUrl,
                            'is_custom' => !empty($item['isCustom']) ? 1 : 0,
                            'source' => 'v2',
                            'update_time' => $now,
                        ];

                        $exists = Db::name('product_background_templates')->where('unique_key', $uniqueKey)->find();
                        if ($exists) {
                            Db::name('product_background_templates')
                                ->where('id', $exists['id'])
                                ->update($data);
                        } else {
                            $data['create_time'] = $now;
                            Db::name('product_background_templates')->insert($data);
                        }

                        $totalSynced++;
                    } catch (\Exception $e) {
                        Log::error('同步单条背景模板失败', ['error' => $e->getMessage(), 'item' => $item]);
                        $output->writeln('  -> 单条失败: ' . $e->getMessage());
                    }
                }

                $pageNo++;
                // 小憩避免打爆接口
                usleep(200000);
            } while (($pageNo - 1) * $pageSize < ($total ?? PHP_INT_MAX));

            $output->writeln('同步完成，总计入库：' . $totalSynced);
        } catch (\Exception $e) {
            Log::error('同步 Product Background 模板失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            $output->writeln('执行失败: ' . $e->getMessage());
        }
    }
}


